package com.zwg.tingshu.order.receiver;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.zwg.tingshu.common.constant.RocketMqConstant;
import com.zwg.tingshu.common.constant.SystemConstant;
import com.zwg.tingshu.common.service.RocketMqService;
import com.zwg.tingshu.model.order.OrderInfo;
import com.zwg.tingshu.order.delay.DelayCloseMessage;
import com.zwg.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: zwg
 * @date: 2025/1/15
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = RocketMqConstant.QUEUE_ORDER_CANCEL,
        selectorExpression = "*",
        consumerGroup = "zwg",
        consumeMode = ConsumeMode.ORDERLY,
        maxReconsumeTimes = 3

)
public class DelayCloseOrderReceiver implements RocketMQListener<String> {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RocketMqService rocketMqService;

    /**
     * 监听用户注册消息；初始化账户（余额）记录
     * 考虑问题：1、是否需要幂等性处理 2、业务中是否需要事务管理
     * 幂等性：同一个消息被多次投递（生产者重发，服务器重发-网络原因），业务执行一次跟多次结果一样
     *
     * @param message
     */
    @Override
    public void onMessage(String message) {
        log.info("监听到延迟订单: {}", message);
        DelayCloseMessage delayCloseMessage = (DelayCloseMessage)JSON.parse(message);
        OrderInfo orderInfo = orderInfoService.selectOrder(Long.valueOf(delayCloseMessage.getData()));
        if(orderInfo != null && SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
            List<Long> times = delayCloseMessage.getTimes();
            if(CollectionUtil.isNotEmpty(times)) {
                // 延迟时间未到，重新投递延迟消息
                Long time = times.remove(0);
                rocketMqService.sendAsync(RocketMqConstant.QUEUE_ORDER_CANCEL, RocketMqConstant.QUEUE_ORDER_CANCEL, JSON.toJSONString(delayCloseMessage));
            } else{
                //延迟时间到  关闭订单
                orderInfoService.orderCancel(Long.valueOf(delayCloseMessage.getData()));
            }
        }
    }
}